package com.zut.Service.SearchImpl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zut.Pojo.Result;
import com.zut.Pojo.problem.Problem;
import com.zut.Pojo.problem.ProblemTag;
import com.zut.Pojo.problem.Tag;
import com.zut.Service.Search;
import com.zut.Service.problemTag;
import com.zut.dao.ProblemDao;
import com.zut.dao.ProblemTagDao;
import com.zut.dao.TagDao;
import lombok.extern.log4j.Log4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
@Log4j
public class SearchImpl implements Search {

    @Autowired
    private ProblemDao problemDao;

    @Autowired
    private ProblemTagDao problemTagDao;

    @Autowired
    private TagDao tagDao;

    /**
     * 题目搜索服务
     * @param keyWords
     * @return
     */
    @Override
    public Result searchByKeyWords(String keyWords) {

        if(StringUtils.isEmpty(keyWords)){
            // 如果关键字为空，则返回数据不能为空的结果
            return Result.builder().data("数据不能为空").build();
        }

// 根据关键字搜索问题
        List<Problem> problems = problemDao.searchByLikes(keyWords);
        log.debug(problems);

        if(CollectionUtils.isEmpty(problems)){
            // 如果搜索结果为空，则返回空数据的结果
            return Result.builder().data(null).build();
        }

// 返回搜索结果
        return Result.builder().data(problems).build();
    }

    @Override
    public Result searchByTag(String tagName) {

        Tag tag = tagDao.selectOne(new QueryWrapper<Tag>().eq("name", tagName));
        if (tag == null) {
            return Result.builder().build(); // 返回空结果或者抛出异常，根据实际需求决定
        }

        List<Problem> problems = problemDao.selectList(new QueryWrapper<Problem>()
                        .inSql("id", "SELECT pid FROM problem_tag WHERE tid = " + tag.getId()))
                .stream()
                .filter(Objects::nonNull) // 过滤掉空结果
                .collect(Collectors.toList());

        return Result.builder().data(problems).build();
    }
}
